package com.woniuxy.demo.epai.controller;


import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.demo.epai.common.Result;
import com.woniuxy.demo.epai.dao.ProductMapper;
import com.woniuxy.demo.epai.model.Product;
import com.woniuxy.demo.epai.model.User;
import com.woniuxy.demo.epai.service.AliPayService;
import com.woniuxy.demo.epai.service.IOrderService;
import com.woniuxy.demo.epai.service.IProductService;
import com.woniuxy.demo.epai.vo.Alivo;
import com.woniuxy.demo.epai.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 订单信息 前端控制器
 * </p>
 *
 * @author epai
 * @since 2021-04-12
 */
@RestController
@RequestMapping("/epai/order")
@Slf4j
public class OrderController {
    @Resource
    private IOrderService iOrderService;
    @Autowired
    private AliPayService aliPayService;
    @Resource
    private IProductService iProductService;
    /**
     * 提供给前端生成订单的接口
     * @return
     */
    @GetMapping("createOrder")
    //uid
    public Result createOrder(Integer pid,Integer uid){

        Integer i  = iOrderService.createOrder(pid,uid);
        return Result.success(i);
    }

    /**
     * 前端用户获取全部订单的接口
     * @return
     */
    @GetMapping("getOrders/{uid}")
    public Result getOrders(@PathVariable Integer uid){


        List<OrderVo> orders = iOrderService.getAllOrders(uid);

        log.info("全部订单：{}",orders);
        return Result.success(orders);
    }
    /**
     * 前端用户获取未付款订单的接口
     * @return
     */
    @GetMapping("getUnpaidOrders")
    public Result getUnpaidOrders(Integer status,Integer uid){


        List<OrderVo> orders = iOrderService.getOrders(status,uid);

        log.info("待付款订单：{}",orders);

        return Result.success(orders);
    }

    /**
     * 支付接口
     * @return
     */
    @PostMapping("pay")
    public String pay(@RequestBody OrderVo orderVo) throws AlipayApiException {
        Integer pid = orderVo.getPid();
        log.info("支付：{}",orderVo);
        Product product = iProductService.queryProductById(pid);
        Alivo alivo = new Alivo();
        //设置订单号
        alivo.setOut_trade_no(orderVo.getOid().toString());
        //设置订单名称
        alivo.setSubject(orderVo.getOid().toString());
        //设置付款金额
        alivo.setTotal_amount(orderVo.getPrice().subtract(orderVo.getBond()).toString());
        //设置订单详情
        alivo.setDescription(orderVo.getIntroduce());
        //获取支付信息详情
        String pay = aliPayService.aliPay(alivo);
        log.info("支付回调参数：{}",pay);
        //执行付款成功后执行修改数据库
        if (!ObjectUtils.isEmpty(pay)){
            aliPayService.aliSuccess(orderVo);
        }
        //返回给前端生成视图
        return pay;
    }
}

